package com.witframework.core.persistence;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.josql.Query;
import org.josql.QueryResults;

import com.witframework.cache.JosqlUtil;

public class MemJdbcDao {
	public static String getTableName(String sql){
		if(sql!=null){
			Pattern p = Pattern.compile("from[\\p{Blank}]*([\\w\\W&&[^\\p{Blank}]])+");
			Matcher m = p.matcher(sql.toLowerCase());
			if (m.find()) {
				String from= m.group().trim();
				return from.substring(4).trim();
			}
		}
		return null;
	}
	private static String getFromTable(String sql){
		if(sql!=null){
			Pattern p = Pattern.compile("from[\\p{Blank}]*([\\w\\W&&[^\\p{Blank}]])+");
			Matcher m = p.matcher(sql.toLowerCase());
			if (m.find()) {
				return m.group().trim();				
			}
		}
		return null;
	}
	public static void main(String[] argv) throws Exception {
		System.out.print(getTableName("select ssd From Table1 Left from"));
	}
	public static List queryListBySql(List memList,String sql,String className){
		sql=sql.replace(getFromTable(sql), "from "+className);
		Query q = JosqlUtil.parse(sql);
		QueryResults clClients = JosqlUtil.execute(q,memList);
		return clClients.getWhereResults();		
	}
	public static int queryCountBySql(List memList,String sql,String className){
		sql=sql.replace(getFromTable(sql), "from "+className);		
		Query q = JosqlUtil.parse(sql);
		QueryResults clClients = JosqlUtil.execute(q,memList);
		return clClients.getWhereResults().size();		
	}
	public static List queryListByObjectName(List memList,Object objectName,String whereVAL){		
		String sql="Select * from "+objectName;
		if(StringUtils.isNotEmpty(whereVAL))
			sql+=" WHERE "+whereVAL;
		Query q = JosqlUtil.parse(sql);
		QueryResults clClients = JosqlUtil.execute(q,memList);
		return clClients.getWhereResults();		
	}
	public static int queryCountByObjectName(List memList,Object objectName,String whereVAL){
		String sql="Select * from "+objectName;
		if(StringUtils.isNotEmpty(whereVAL))
			sql+=" WHERE "+whereVAL;
		Query q = JosqlUtil.parse(sql);
		QueryResults clClients = JosqlUtil.execute(q,memList);
		return clClients.getWhereResults().size();		
	}
}
